#include "Scene1.h"
#include "SimpleAudioEngine.h"

using namespace cocos2d;
using namespace CocosDenshion;
USING_NS_CC;

CCScene* Scene1::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    Scene1 *layer = Scene1::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool Scene1::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(Scene1::menuCloseCallback) );
    pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition( CCPointZero );
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    // add "HelloWorld" splash screen"
    
    background = CCSprite::create("blue-shooting-stars.png");
    background->setAnchorPoint(ccp(0,0));
    this->addChild(background);
    
    
    _clouds = new CCArray;
    for (int ii=0; ii<6; ii++)
    {
        CCSprite *cloud=CCSprite::create("csloues-th.png");
        
        int cloudHeight = cloud->getContentSize().height;
        int cloudWidth = cloud->getContentSize().width;
        int minY = cloudHeight/2;
        int maxY = winSize.height-minY;
        int rangeY = maxY - minY;
        
        int minX = cloudWidth/2;
        int maxX = winSize.width-minX;
        int rangeX = maxX - minX;
        
        CCObject *element;
        
        int randY;
        int randX;
        bool flag = true;
        while (flag==true)
        {
          randY = randomValueBetween(minY, rangeY);
          randX = randomValueBetween(minX, rangeX);
          CCRect rect = CCRectMake(randX-cloudWidth/2,
                                   randY-cloudHeight/2,
                                   cloudWidth,cloudHeight);
          if (_clouds->count()==0)
          {
              break;
          }
          CCARRAY_FOREACH(_clouds, element)
          {
              CCSprite *ele = (CCSprite*)element;
              if (CCRect::CCRectIntersectsRect(ele->boundingBox(), rect))
              {
                  flag = true;
                  break;
              }
              else {
                  flag=false;
              }
          }
        }
        cloud->setPosition(ccp(randX,randY));
        this->addChild(cloud, 0);
        _clouds->addObject(cloud);
        floatingDistance=30;
        cloud->runAction(CCRepeatForever::create(
                                                  (CCSequence*)CCSequence::create(                                                                                          CCMoveBy::create(1.0f+CCRANDOM_0_1(),ccp(0,floatingDistance)                                                                                                                       ),
                                                                                  CCMoveBy::create(1.0f+CCRANDOM_0_1(),ccp(0,-floatingDistance)
                                                                                                   ),
                                                                                  NULL)
                                                  )
                          );
        
    
        

    }
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
    SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("All Fall Down (Theme).mp3");
    SimpleAudioEngine::sharedEngine()->playBackgroundMusic("All Fall Down (Theme).mp3",true);

    return true;
}


void Scene1::selectSpriteForTouch(CCPoint touchLocation)
{
    CCSprite* newSprite=NULL;
    CCObject *element;
    CCARRAY_FOREACH(_clouds, element)
    {
        CCSprite* ele = (CCSprite*)element;
        if (CCRect::CCRectContainsPoint(ele->boundingBox(),touchLocation))
        {
            newSprite = ele;
            break;
        }
        
    }
    if (newSprite!=selSprite)
    {   if (newSprite!=NULL)
        {
            newSprite->stopAllActions();
            selSprite = newSprite;
        }
    }
}

bool Scene1::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
    CCPoint touchLocation = convertTouchToNodeSpace(touch);
    selectSpriteForTouch(touchLocation);
    return true;
}


void Scene1::ccTouchMoved(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{

    CCPoint touchLocation = convertTouchToNodeSpace(touch);
    
    CCPoint oldTouchLocation = touch->previousLocationInView();
    oldTouchLocation = CCDirector::sharedDirector()->convertToGL(oldTouchLocation);
    oldTouchLocation = convertToNodeSpace(oldTouchLocation);
    
    CCPoint translation = ccpSub(touchLocation, oldTouchLocation);
    panForTranslation(translation);

}

void Scene1::panForTranslation(CCPoint translation)
{
    if (selSprite){
        CCPoint newPos = ccpAdd(selSprite->getPosition(), translation);
        selSprite->setPosition(newPos);
    }
    else {
        CCPoint newPos = ccpAdd(getPosition(), translation);
        setPosition(boundLayerPos(newPos));
    }
}

CCPoint Scene1::boundLayerPos(CCPoint newPos)
{
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCPoint retval = newPos;
    retval.x = MIN(retval.x, 0);
    retval.x = MAX(retval.x, -background->getContentSize().width+winSize.width);
    retval.y = getPosition().y;
    return retval;
    
}

void Scene1::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

float Scene1::randomValueBetween( float low , float high ) {
    return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
}

void Scene1::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
    if (selSprite!=NULL) {
    selSprite->runAction(CCSequence::create(CCScaleBy::create(0.125f, 1.111f),
                                            CCScaleBy::create(0.125f, 0.9),
                                            NULL));
   
    selSprite->runAction(CCRepeatForever::create(
                                      (CCSequence*)CCSequence::create(CCMoveBy::create(1.0f+CCRANDOM_0_1(),ccp(0,floatingDistance)),
                                                                      CCMoveBy::create(1.0f+CCRANDOM_0_1(),ccp(0,-floatingDistance)),
                                                                      NULL)
                                      )
              );
    
    }
    selSprite = NULL;
}

Scene1::~Scene1()
{
    if (_clouds)
    {
        _clouds->release();
        _clouds = NULL;
    }
}

